package com.frxuexi.demo.news

import androidx.paging.PagingSource
import androidx.paging.PagingState
import com.frxuexi.base.entity.RecordEntity
import com.frxuexi.base.net.ApiServiceNews

class NewsDataSource(val apiServiceNews: ApiServiceNews):PagingSource<Int,RecordEntity>() {
    override fun getRefreshKey(state: PagingState<Int, RecordEntity>): Int? {
        return null
    }

    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, RecordEntity> {
        return try {
            //获取当前页码
            var currentPage=params.key?:1
            val news = apiServiceNews.getNews(currentPage)
            val nextPage=if(news.data.records.size!=0) currentPage+1 else null
//            val nextPage=if(currentPage<news.data.pages) currentPage+1 else null
            val prePage=if(currentPage>1) currentPage-1 else null
            return LoadResult.Page(news.data.records,prePage,nextPage)
        }catch (e:Exception){
            return LoadResult.Error(e)
        }
    }
}